# coding: utf-8
# @Author: 健聪
# @Description:
# @Date: 2024/10/12
import time
from flask import Flask, request, make_response, session

# 应用初始化
app = Flask(__name__)
app.config['SECRET_KEY'] = 'demo1'


# 路由与视图函数
@app.route('/')
def hello_word():
    return 'Hello World!'


@app.route('/user/<username>')
def user(username):
    return "This is %s page" % username


@app.route('/info')
def info():
    info_str = '用户ip: %s<br />用户浏览器：%s' % (request.remote_addr, request.user_agent.string)
    return info_str


@app.route('/sign_in')
def sign_in():
    # 设置session持久性存储，关闭浏览器不失效
    session.permanent = True

    # 从session获取最后签到时间以及签到次数
    sign_in_time_prev = session.get('sign_in_time_prev', '未知')
    sign_in_count = session.get('sign_in_count', 1)

    # 设置session，使用方式与dict类似
    session['sign_in_time_prev'] = time.strftime('%Y-%m-%d %H:%M:%S')
    session['sign_in_count'] = sign_in_count + 1

    ## 删除特定 session
    # session.pop('sign_in_time_prev')
    # session.pop('sign_in_count')
    ## 清空所有session
    # session.clear()

    return '你上一次签到的时间是：%s<br />这是你第%d次签到' % (sign_in_time_prev, sign_in_count)


@app.route('/access')
def access():
    # 从cookie获取最后访问时间
    last_access_time = request.cookies.get('last_access_time', '未知')
    resp = make_response('你最后访问的时间是：%s' % last_access_time)

    # 获取服务器当前时间并设置cookie
    last_acccess_time = time.strftime('%Y-%m-%d %H:%M:%S')
    # max_age用于设置cookie的有效期（秒）86400 = 24小时  3600 = 1小时
    resp.set_cookie('last_access_time', last_access_time, max_age=3600)

    ## 手动删除cookie
    # resp.delete_cookie('last_access_time')

    return resp


if __name__ == '__main__':
    app.run()
